<?php 
	// header('Content-Type: application/json; charset=cp1251_general_ci');
	header('Content-Type: application/json; charset=UTF-8');
	$arrResult = array();
	$arrResult['result'] = false;
	$arrResult['content'] = '';
	if(isAdmin() && isset($_GET['action'])) {
		switch($_GET['action']){
			case 'edit_desc':
//				var_dump($_GET);
				$descData = $desc->update($_GET['desc'], $_GET['description']);
				$arrResult['result'] = true;
				break;
			case 'get_desc':
				$descKey = $_GET['desc'];
				$descData = $desc->get($descKey);
				$arrResult['content'] = trim("
						<script type='text/javascript'>
							function sendData(){
								console.log('sendData');
								var content = $('.content');
								var sendData = '';
								sendData += '&description='+content.find('[name=description]').val();
								query('admin&action=edit_desc&desc={$descKey}&uid={$_SESSION['user_id']}'+sendData, function(data){
									HtmlBox.hide();
								});
							}
						</script>
						<div class='content' style='width:800px; height: 400px; padding:10px;margin:0px;'> 
							description: </br>
							<textarea style=\"width:800px;height: 400px;\" name='description' value='{$descData}'>{$descData}</textarea>
							<button onclick='sendData();'>update information</button>
						</div>
				", "\t");
				$arrResult['result'] = true;
				break;
			case 'delete_item':
				$id = $_GET['item'];
				deleteItem($id);
				$arrResult['result'] = true;
				break;
			case 'edit_item':
				$id = $_GET['item'];
				$itemData = getItem($id);
				$arrResult['result'] = true;
				//$status = '';
				$types = '';
				$enums = getEnumValues('items', 'status');
				$typesArr = getTypeValues();
				$types .="<select  id='itemType'>\n";
				//var_dump($typesArr);
				foreach($typesArr as $value) {
					$selected = $value['id']==$itemData["type"]?"selected":"" ;
					$types .="<option ".$selected." value='{$value['id']}'>{$value['type']}</option>\n";
				}
				$types .="</select>\n";
				
				$statuses = '';
				$statuses .="<select id='status'>\n";
				foreach($enums as $value) {
					$selected = $value==$itemData["status"]?"selected":"" ;
					$statuses .="<option ".$selected." value='{$value}'>{$value}</option>\n";
				}
				// var_dump($itemData);
				$statuses .="</select>\n";
	
				$arrResult['content'] = trim("
						<script type='text/javascript'>
							function sendData(){
								console.log('sendData');
								var content = $('.content');
								var sendData = '';
								sendData += '&name='+content.find('[name=name]').val();
								sendData += '&description='+content.find('[name=description]').val();
								sendData += '&cost='+content.find('[name=cost]').val();
								sendData += '&cost_for_hire='+content.find('[name=cost_for_hire]').val();
								sendData += '&img='+content.find('[name=img]').val();
								sendData += '&type='+content.find('#itemType option:selected').val();
								sendData += '&status='+content.find('#status option:selected').val();
								query('admin&action=update_item&item={$id}&uid={$_SESSION['user_id']}'+sendData, function(data){
									HtmlBox.hide();
									reloadTab(false);
								});
							}
						</script>
						<div class='content' style='width:400px; padding:10px;margin:0px;'> 
							<input name='name' value='{$itemData["name"]}'/> name</br>
							<textarea name='description' value='{$itemData["description"]}'>{$itemData["description"]}</textarea>description</br>
							<input name='cost' value='{$itemData["cost"]}'/> cost</br>
							<input name='cost_for_hire' value='{$itemData["cost_for_hire"]}'/> cost for hire</br>
							<input name='img' value='{$itemData["img"]}'/> img</br>
							{$types} type </br>
							{$statuses} status</br>
							<button onclick='sendData();'>update information</button>
							
						</div>
				", "\t");
				break;
			case 'update_item':
				updateItem($_GET['item']);
				$arrResult['result'] = true;
				break;
			case 'save_new_item':
				/*$fp = fopen('data.txt', 'w');
				var_dump($_GET);
				$data = ob_get_clean();
				fwrite($fp, $data);
				fwrite($fp, '1');
				fwrite($fp, '2');
				fwrite($fp, '3');
				fclose($fp);
				var_dump($_GET);*/
				addItem();
				break;
			case 'add_new_item':
				$arrResult['result'] = true;
				//$status = '';
				$types = '';
				$enums = getEnumValues('items', 'status');
				$typesArr = getTypeValues();
				$types .="<select  id='itemType'>\n";
				//var_dump($typesArr);
				foreach($typesArr as $value) {
					$types .="<option value='{$value['id']}'>{$value['type']}</option>\n";
				}
				$types .="</select>\n";
				
				$statuses = '';
				$statuses .="<select id='status'>\n";
				foreach($enums as $value) {
					$statuses .="<option value='{$value}'>{$value}</option>\n";
				}
				$statuses .="</select>\n";
				$arrResult['content'] = trim("
						<script type='text/javascript'>
							function sendData(){
								console.log('sendData');
								var content = $('.content');
								var sendData = '';
								sendData += '&name='+content.find('[name=name]').val();
								sendData += '&description='+content.find('[name=description]').val();
								sendData += '&cost='+content.find('[name=cost]').val();
								sendData += '&cost_for_hire='+content.find('[name=cost_for_hire]').val();
								sendData += '&img='+content.find('[name=img]').val();
								sendData += '&type='+content.find('#itemType option:selected').val();
								sendData += '&status='+content.find('#status option:selected').val();
								query('admin&action=save_new_item&uid={$_SESSION['user_id']}'+sendData, function(data){
									HtmlBox.hide();
									reloadTab(false);
								});
							}
						</script>
						<div class='content' style='width:400px; padding:10px;margin:0px;'> 
							<input name='name'/> name</br>
							<input name='description' /> description</br>
							<input name='cost' /> cost</br>
							<input name='cost_for_hire' /> cost for hire</br>
							<input name='img' /> img</br>
							{$types} type </br>
							{$statuses} status</br>
							<button onclick='sendData();'>add new item</button>
							
						</div>
				", "\t");
				break;
		}
	}
	
	function deleteItem($id) {
		$query= "DELETE FROM `items` WHERE id={$id}";
		$result = mysql_query( $query ) or die( 'error delete item for id: {$id}' . mysql_error() );
	}
	function updateItem($id) {
		
		$query= "UPDATE `items` 
			SET 
				".getUpdateField('name', ',')."
				".getUpdateField('description', ',')."
				".getUpdateField('cost', ',')."
				".getUpdateField('cost_for_hire', ',')."
				".getUpdateField('img', ',')."
				".getUpdateField('status', ',')."
				".getUpdateField('type', '')."
			WHERE id={$id}
		";
		//echo $query."\n";
		$result = mysql_query( $query ) or die( 'error update item ' . mysql_error() );
	}
	function getUpdateField($fieldName, $seperator) {
		if(isset($_GET[$fieldName])){
			return " `{$fieldName}`='{$_GET[$fieldName]}'".$seperator;
		}
		return "";
	}
	function addItem() {
		$query= "INSERT INTO `items` (`name`, `description`, `cost`, `cost_for_hire`, `img`, `status`, `type`) 
			VALUES 
			('{$_GET['name']}', '{$_GET['description']}', '{$_GET['cost']}', '{$_GET['cost_for_hire']}', '{$_GET['img']}', '{$_GET['status']}', '{$_GET['type']}')";
		//echo $query;
		$result = mysql_query( $query ) or die( 'error insert new item ' . mysql_error() );
	}
	function getItem($id) {
		$query= "select * FROM `items` WHERE id=".$id."";
		//echo $query."\n";
		$result = mysql_query( $query ) or die( 'error get item by id: '.$id." ". mysql_error() );
		return mysql_fetch_assoc($result);
		//$result = mysql_query( $query ) or die( 'error insert new item ' . mysql_error() );
		
	}
	function getTypeValues() {
		$query = "SELECT id, type 
			FROM  `item_types`";
		$result = mysql_query( $query ) or die( 'error getting item types ' . mysql_error() );
		$resultList = array();
		$index = 0;
		while ($row = mysql_fetch_assoc($result)) {
			$resultList[$index]['type'] = $row['type'];
			$resultList[$index]['id'] = $row['id'];
			$index++;
		}
		return $resultList;
	}
	
	function getEnumValues($table, $field) {
		$query = " SHOW COLUMNS FROM `$table` LIKE '$field' ";
		$result = mysql_query( $query ) or die( 'error getting enum field ' . mysql_error() );
		$row = mysql_fetch_array( $result , MYSQL_NUM );
		$regex = "/'(.*?)'/";
		preg_match_all( $regex , $row[1], $enum_array );
		$enum_fields = $enum_array[1];
		return( $enum_fields );
	}
	
	function isAdmin(){
		if(isset($_SESSION['user_name']) && isset($_SESSION['user_id']) && isset($_GET['uid'])) {
			$arr = array("9153971", "2362690", "8309790", "7842042");
			if(array_search($_GET['uid'], $arr) !=-1) {
				return true;
			}
		}
		return false;
	}
	$arrResult["detect_encoding"] = mb_detect_encoding($arrResult["content"], "auto");
	$json = json_encode($arrResult);
	$json_decode = json_decode($json);
	if(!isset($json_decode->content) || $json_decode->content == null || $json_decode->content == ""){
		$json = json_encode(array_map('utf8_encode', $arrResult), JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE	);
	}
	echo $json;
?>